<template>
	<div class="detailHeader">
		<el-collapse v-model="activeNames">
			<el-collapse-item title="船货信息" name="1">
        <el-form :model="formData" ref="ruleForm" label-width="130px" class="demo-ruleForm">
					<el-row :gutter="20">
            <el-col :span="8">
							<el-form-item label="船名航次" prop="shipvoyageName" class="top">
								<el-input
									v-model="formData.shipvoyageName"
									size="mini"
									placeholder="请输入船名"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="提单号" prop="billNo" class="top">
								<el-input
									v-model="formData.billNo"
									size="mini"
									placeholder="请输入提单号"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="货主" prop="cargoOwnerName" class="top">
								<el-input
									v-model="formData.cargoOwnerName"
									size="mini"
									placeholder="请输入货主"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="开证公司" prop="issuingCompanyName" class="top">
								<el-input
									v-model="formData.issuingCompanyName"
									size="mini"
									placeholder="请输入开证公司"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="提单数" prop="billQuantity" class="top">
								<el-input
									v-model="formData.billQuantity"
									size="mini"
									placeholder="请输入提单数"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="检尺数" prop="shipperName" class="top">
								<el-input
									v-model="formData.shipperName"
									size="mini"
									placeholder="请输入检尺数"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="未放货数" prop="unreleaseQuantity" class="top">
								<el-input
									v-model="formData.unreleaseQuantity"
									size="mini"
									placeholder="请输入未放货数"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="提单体积" prop="billVolume" class="top">
								<el-input
									v-model="formData.billVolume"
									size="mini"
									placeholder="请输入提单体积"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="检尺体积" prop="shipperName" class="top">
								<el-input
									v-model="formData.shipperName"
									size="mini"
									placeholder="请输入检尺体积"
									disabled
								/>
							</el-form-item>
						</el-col>
            <el-col :span="24">
							<el-form-item label="备注" class="top">
                <div slot="label" style="display:inline-block" :style="{width:'150px'}">
                  <span style="margin-right: 20px;">备注</span>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="boatRemarksSave"
                  >保存</el-button>
                </div>
								<el-input
									type="textarea"
									:rows="2"
									placeholder="请输入备注"
									v-model="remark"
								></el-input>
							</el-form-item>
						</el-col>

					</el-row>
				</el-form>
			</el-collapse-item>
      <el-collapse-item title="货权转让" name="2">
        <el-form :model="formData" ref="ruleForm" label-width="110px" class="demo-ruleForm">
					<el-row :gutter="20">
            <el-col :span="12">
							<el-form-item label="起止日期" prop="shipperName" class="left">
								<el-date-picker
									v-model="timeRange"
									type="datetimerange"
                  size="mini"
									placeholder="请选择起止日期"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH"
								></el-date-picker>
							</el-form-item>
						</el-col>
            <el-col :span="2.4" v-for="item in buttonList" :key="item.label">
							<el-form-item label="" class="top">
								<el-button 
									:type="item.type" 
									size="mini" 
                  :disabled="item.disabled"
									@click="buttonClick(item.click)">
									{{item.label}}
								</el-button>
							</el-form-item>
						</el-col>
            <el-col :span="24">
							<el-form-item label="" prop="shipperName" class="top">
								<el-card class="bgcard">总件数：{{quantity}} 总重量：{{ton}} 总体积：{{volume}}</el-card>
							</el-form-item>
						</el-col>
            <el-col :span="24">
							<el-form-item label="" prop="shipperName" class="top">
								<BaseTable
                  :data="tableData"
                  :columns="tableColumn"
                  :tableHeight="300"
                  :pagination="false"
				  @details="tableClick"
                ></BaseTable>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-collapse-item>
		</el-collapse>
    <!-- 货权转移 -->
		<el-drawer
			:before-close="handleClose"
			title="货权转移"
			:visible.sync="cargoTransfer"
      :append-to-body="true"
			direction="rtl"
			size="40%"
		>
      <cargoTransfer
        ref="cargoTransfer"
        :customerData="customerData"
      />
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="cargoTransferSave" size="mini">保 存</el-button>
        <el-button size="mini" @click="cargoTransfer = false">取消</el-button>
			</div>
		</el-drawer>
    <!-- 货权转移附件查询 -->
    <el-dialog
      title="货权转移附件"
      :visible.sync="openFile"
      width="30%"
      :before-close="handleClose"
      append-to-body>
      <div 
        v-for="(item,index) in fileList" :key="item.fileId" 
        @click="handlePreview(item)"
        style="cursor:pointer;margin: 5px 0;"
      >{{index + 1}}、{{item.fileName}}
      </div>
      <el-empty description="未上传附件" v-if="fileList.length === 0"></el-empty>
      
    </el-dialog>
    <el-dialog
      title="预览"
      append-to-body
      :visible.sync="dialogVisible"
      width="90%"
      top="3vh"
    >
      <img :src="imgurl" style="width:100%;height:auto"/>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="downLoadFile(fileInfo)">下载</el-button>
      </span>
    </el-dialog>
	</div>
</template>

<script>
import BaseTable from '@/components/BaseTable'
import api from '@/api/Business/issuingCompany'
import cargoTransfer from './cargoTransfer.vue'
import Utils from '@/libs/Utils.js'
import publicapi from '@/api/public'
import axios from 'axios'
import config from '@/network/config.js'
export default {
  name: 'detail',
  components: { BaseTable, cargoTransfer },
  props: {
    customerData: {
      type: Array
    }
  },
  data() {
    return {
      activeNames: ['1', '2'],
      formData: {
      }, // from
      timeRange: [],
      buttonList: [
        { label: '查询', type: 'primary', icon: '', disabled: false, click: () => this.getCargoTransfer() },
        { label: '添加货转', type: 'primary', icon: '', disabled: false, click: () => this.addCargoTransfer('add') },
        { label: '编辑', type: 'primary', icon: '', disabled: true, click: () => this.addCargoTransfer('edit') },
        { label: '删除', type: 'danger', icon: '', disabled: true, click: () => this.deleteCargoTransfer() }
      ],
      tableData: [], // form表单table数据
      tableColumn: [ // table表头
        { prop: 'transferDate', label: '货转日期' },
        { prop: 'quantity', label: '货转件数' },
        { prop: 'ton', label: '货转重量' },
        { prop: 'volume', label: '货转体积' },
        { prop: 'remark', label: '备注' },
        { prop: 'createName', label: '创建人' },
        { prop: 'createTime', label: '创建时间' },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 120,
          render: (h, params) => {
            return h(
              'div',

              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML:
                      "<span style='color:#0B6CD6'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>查看附件</span></span>"
                  },
                  on: {
                    click: () => {
                      this.viewFile(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      remark: '', // 提单备注
      clickRow: {},
      cargoRow: {},
      cargoTransfer: false, // 货转抽屉
      openFile: false, // 货转查看附件dialog
      fileList: [], // 预览附件
      quantity: 0,
      ton: 0,
      volume: 0,
      imgurl: '',
      dialogVisible: false,
      fileInfo: {}
    }
  },
  computed: {
  },
  methods: {
    /**
     * 船货信息备注保存功能
     */
    async boatRemarksSave() {
      const res = await api.reqEditBillRemark({ cargoInfoId: this.clickRow.cargoInfoId, remark: this.remark })
      if (res.data.code === '0000') {
        this.$message.success('备注修改成功！')
      }
    },
    /**
     * 货权转让的查询功能
     */
    async getCargoTransfer() {
      const res = await api.reqGetCargoTransfer({ cargoInfoId: this.clickRow.cargoInfoId, startTime: this.timeRange[0], endTime: this.timeRange[1] })
      this.buttonList[2].disabled = true
      this.buttonList[3].disabled = true
      this.tableData = res.data.data.transferList
      this.quantity = res.data.data.quantity
      this.ton = res.data.data.ton
      this.volume = res.data.data.volume
      this.formData.unreleaseQuantity = res.data.data.unreleaseQuantity
    },
    /**
     * 添加货权转让
     */
    addCargoTransfer(type) {
      this.cargoTransfer = true
      this.$nextTick(() => {
        // 如果是编辑则将点击行信息付给formData
        if (type === 'edit') { // 编辑进来赋值
          this.$refs.cargoTransfer.formData.transferDate = this.cargoRow.transferDate
          this.$refs.cargoTransfer.formData.cargoOwnerId = this.cargoRow.cargoOwnerId
          this.$refs.cargoTransfer.formData.cargoOwnerName = this.cargoRow.cargoOwnerName
          this.$refs.cargoTransfer.formData.cargoAgentId = this.cargoRow.cargoAgentId
          this.$refs.cargoTransfer.formData.cargoAgentName = this.cargoRow.cargoAgentName
          this.$refs.cargoTransfer.formData.storageDate = this.cargoRow.storageDate
          this.$refs.cargoTransfer.formData.quantity = this.cargoRow.quantity
          this.$refs.cargoTransfer.formData.ton = this.cargoRow.ton
          this.$refs.cargoTransfer.formData.volume = this.cargoRow.volume
          this.$refs.cargoTransfer.formData.remark = this.cargoRow.remark
          this.$refs.cargoTransfer.formData.id = this.cargoRow.id
          this.$refs.cargoTransfer.formData.mattachmentInfoList = [] // 先清空
          this.cargoRow.mattachmentInfoList.forEach(item => {
            item.name = item.fileName
            this.$refs.cargoTransfer.formData.mattachmentInfoList.push(item)
          })
        } else { // 新增进来清空
          this.$refs.cargoTransfer.$refs.ruleForm.resetFields()
          this.$refs.cargoTransfer.formData.id = ''
          this.$refs.cargoTransfer.formData.mattachmentInfoList = []
        }
        // 将id和对应字段填进去
        this.$refs.cargoTransfer.formData.cargoInfoIdSource = this.clickRow.cargoInfoId
        this.$refs.cargoTransfer.formData.billId = this.clickRow.id

        this.$refs.cargoTransfer.yph = this.clickRow.cargoOwnerName + '/' + this.clickRow.cargoAgentName + '/' + this.clickRow.cargoName + '/' + this.clickRow.tradeType + '/' + this.clickRow.shipvoyageName
      })
    },
    /**
     * 货权转移保存
     */
    async cargoTransferSave() {
      const params = this.$refs.cargoTransfer.formData

      this.$refs.cargoTransfer.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (params.id) { // 编辑
            api.reqEditTransfer(params).then(res => {
              if (res.data.code === '0000') {
                this.cargoTransfer = false
                this.$message.success('货权转移成功')
                for (const key in params) {
                  params[key] = ''
                }
                this.$refs.cargoTransfer.$refs.ruleForm.resetFields()
                this.getCargoTransfer()
              }
            })
          } else { // 新建
            api.reqAddTransfer(params).then(res => {
              if (res.data.code === '0000') {
                this.cargoTransfer = false
                this.$message.success('货权转移成功')
                for (const key in params) {
                  params[key] = ''
                }
                this.$refs.cargoTransfer.$refs.ruleForm.resetFields()
                this.getCargoTransfer()
              }
            })
          }
        } else {
          this.$message.warning('请完善表单数据')
          return false;
        }
      });
    },
    /**
     * 删除货转
     */
    deleteCargoTransfer() {
      this.$confirm('此操作将撤销此货种，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDelete(this.cargoRow.id).then(res => {
          if (res.data.code === '0000') {
            this.$message.success('撤销成功')
            this.getCargoTransfer()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消撤销'
        });
      });
    },
    /**
     * 货权查询中查看附件
     */
    viewFile(row) {
      this.openFile = true
      console.log(row, 'row');
      this.fileList = row.mattachmentInfoList
    },
    /**
     * 预览附件
     */
    handlePreview(file) {
      this.fileInfo = file
      if (file.fileName.indexOf('jpg') !== -1 || file.fileName.indexOf('png') !== -1 || file.fileName.indexOf('jpeg') !== -1) {
        axios({
          method: 'get',
          url: `${config.ConfigBaseURL}/wfpms-master-service/api/external/publics/file/down?id=${file.fileId}`,
          responseType: 'arraybuffer',
          params: {
            token: window.sessionStorage.getItem('token')
          }
        }).then(res => {
          const blob = new Blob([res.data], {
            type: 'application/png;charset=utf-8'
          });
          const url = window.URL.createObjectURL(blob);
          this.imgurl = url
          this.dialogVisible = true
        })
      } else {
        this.downLoadFile(file)
      }
    },
    /**
     * 下载附件
     */
    async downLoadFile(file) {
      const res = await publicapi.down(file.fileId)
      const content = res.data
      const blob = new Blob([content]) // 构造一个blob对象来处理数据
      const link = document.createElement('a') // 创建a标签
      link.download = file.fileName // a标签添加属性
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob, {
        type: `application/pdf`
      })
      document.body.appendChild(link)
      link.click() // 执行下载
      URL.revokeObjectURL(link.href) // 释放url
      document.body.removeChild(link) // 释放标签
    },
    /**
     * 获取行信息
     */
    tableClick(row) {
      this.cargoRow = row
      this.buttonList[2].disabled = false
      this.buttonList[3].disabled = false
    },
    /**
     * 按钮事件
     */
    buttonClick(i, e) {
      console.log(e, 'eee');

      i()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.cargoTransfer) {
        oldV = this.cargoFormData
        newV = this.$refs.cargoTransfer.formData
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "~@/assets/form.less";

[v-cloak] {
	display: none;
}
</style>
